# Static resource management blueprint

from flask import Blueprint, request, send_from_directory, jsonify
from flask_cors import CORS
from database.postgre_singleton import PostgreSingleton
from database.wx_user_info_extend_methods import WxUserInfoExtendTableMethods
from database.wx_user_table_methods import WxUserTableMethods
import psycopg2.extras
import os
from qrcode_methods import generate_qr_code
import logging
from flask import send_file


static_resource_bp = Blueprint('static_resource', __name__)
CORS(static_resource_bp)  # 允许跨域请求

# 设置静态资源存储目录
UPLOAD_FOLDER = 'upload'
if not os.path.exists(UPLOAD_FOLDER):
    os.makedirs(UPLOAD_FOLDER)




def allowed_file(filename):
    # csv文件后缀名
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ['png', 'jpg', 'jpeg']

# 上传文件接口
@static_resource_bp.route('/upload', methods=['POST'])
def upload():

    open_id = request.form.get('open_id')

    wx_avatar_or_QR_code = request.form.get('wx_avatar_or_QR_code')

    if open_id is None or wx_avatar_or_QR_code is None:
        return jsonify({
            "status": -1,
            "errorCode": 1007,
            "errorMsg": "Invalid parameters",
            "resultBody": None
        })
    
    if wx_avatar_or_QR_code not in ["avatar", "QR_code", "practicing_certificate", "personal_photo", "curriculum_vitae"]:
        return jsonify({
            "status": -1,
            "errorCode": 1008,
            "errorMsg": "Invalid wx_avatar_or_QR_code",
            "resultBody": None
        })

    if 'file' not in request.files:
        return jsonify({
            "status": -1,
            "errorCode": 1000,
            "errorMsg": "No file part",
            "resultBody": None
        })
    file = request.files['file']

    if file.filename == '':
        # return jsonify({'error': 'No selected file'}), 400

        return jsonify({
            "status": -1,
            "errorCode": 1001,
            "errorMsg": "No selected file",
            "resultBody": None
        })
    
    if not file:

        return jsonify({
            "status": -1,
            "errorCode": 1004,
            "errorMsg": "File not found",
            "resultBody": None
        })
    
    elif not allowed_file(file.filename):
        return jsonify({
            "status": -1,
            "errorCode": 1005,
            "errorMsg": "File type not allowed",
            "resultBody": None
        })
    
    # 文档大小限制不超过3M
    elif file.content_length > 1024 * 1024 * 3:
        return jsonify({
            "status": -1,
            "errorCode": 1002,
            "errorMsg": "File size exceeds 1M",
            "resultBody": None
        })
    
    # elif file.filename in os.listdir(UPLOAD_FOLDER):
    #     return jsonify({
    #         "status": -1,
    #         "errorCode": 1003,
    #         "errorMsg": "File already exists",
    #         "resultBody": None
    #     })
    
    else:
        file.filename = f"{open_id}_{wx_avatar_or_QR_code}.{file.filename.rsplit('.', 1)[1].lower()}"
        
        # 保存头像文件到指定目录 头像文件名为open_id，后缀名根据文件类型
        filename = os.path.join(UPLOAD_FOLDER, file.filename)
        try:
            file.seek(0)
            file.save(filename)

        except Exception as e:
            file.close()
            return jsonify({
                "status": -1,
                "errorCode": 1006,
                "errorMsg": f"Failed to save file: {e}",
                "resultBody": None
            })
        else:

            file.close()
            # return jsonify({'message': f'File uploaded successfully: {file.filename}'}), 201


            # 保存头像文件路径到数据库
            with PostgreSingleton() as conn:
                cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
                user_id = WxUserTableMethods(conn, cur).get_user_by_open_id(open_id)["user_id"]

                if wx_avatar_or_QR_code == "avatar":
                    WxUserInfoExtendTableMethods(conn, cur).add_avatar_name(user_id, file.filename)
                    conn.commit()

                if wx_avatar_or_QR_code == "QR_code":
                    WxUserInfoExtendTableMethods(conn, cur).add_wx_QR_code(user_id, file.filename)



        return jsonify({
            "status": 1,
            "errorCode": None,
            "errorMsg": None,
            "resultBody": f"https://tt.bainarm.cn/tt/api/view/{file.filename}"
        })
# 生成分享二维码接口 
@static_resource_bp.route("/generate_share_qr_code", methods=['POST'])
def generate_share_qr_code():
    
    recommend_user_id = request.form.get('recommend_user_id')
    if recommend_user_id is None:
        return jsonify({
            "status": -1,
            "errorCode": 1007,
            "errorMsg": "Invalid parameters",
            "resultBody": None
        })
    # def generate_qr_code(url, filename='qr_code.png'):
    # 生成分享二维码
    qr_code_name = f"{recommend_user_id}_share_QR_code.png"
    url = f"https://tt.bainarm.cn/pages/index/index?id={recommend_user_id}"
    generate_qr_code(url, filename=os.path.join(UPLOAD_FOLDER, qr_code_name))

    return jsonify({
        "status": 1,
        "errorCode": None,
        "errorMsg": None,
        "resultBody": f"https://tt.bainarm.cn/tt/api/view/{qr_code_name}"
    })

# 下载文件接口
@static_resource_bp.route('/download/<filename>', methods=['GET'])
def download_file(filename):
    if filename not in os.listdir(UPLOAD_FOLDER):
        # return jsonify({'error': 'File not found'}), 404
        return jsonify({
            "status": -1,
            "errorCode": 1006,
            "errorMsg": "File not found",
            "resultBody": None
        })
    return send_from_directory(UPLOAD_FOLDER, filename, as_attachment=True)




# 显示图片接口
@static_resource_bp.route('/view/<filename>', methods=['GET'])
def view_image(filename):
    if filename not in os.listdir(UPLOAD_FOLDER):
        return jsonify({
            "status": -1,
            "errorCode": 1006,
            "errorMsg": "File not found",
            "resultBody": None
        })
    
    try:
        # 使用send_file返回图片，以便在网页上展示
        return send_file(os.path.join(UPLOAD_FOLDER, filename), mimetype='image/jpeg')
    except Exception as e:
        return jsonify({
            "status": -1,
            "errorCode": 1007,
            "errorMsg": f"Error occurred: {str(e)}",
            "resultBody": None
        })


# 删除文件接口
@static_resource_bp.route('/delete/<filename>', methods=['DELETE'])
def delete_file(filename):
    file_path = os.path.join(UPLOAD_FOLDER, filename)
    if os.path.exists(file_path):
        os.remove(file_path)
        # return jsonify({'message': 'File deleted successfully'}), 200
        return jsonify({
            "status": 1,
            "errorCode": None,
            "errorMsg": None,
            "resultBody": "File deleted successfully"
        })
    else:
        # return jsonify({'error': 'File not found'}), 404
        return jsonify({
            "status": -1,
            "errorCode": 1000,
            "errorMsg": "File not found",
            "resultBody": None
        })

# 展示文件列表接口
@static_resource_bp.route('/files', methods=['GET'])
def list_files():
    files = os.listdir(UPLOAD_FOLDER)
    # return jsonify({'files': files}), 200
    # 获取文件大小及创建时间

    file_info = []
    for file in files:
        file_path = os.path.join(UPLOAD_FOLDER, file)
        file_size = os.path.getsize(file_path)
        file_ctime = os.path.getctime(file_path)
        file_info.append({
            "filename": file,
            "size": file_size,
            "ctime": file_ctime
        })
    return jsonify({
        "status": 1,
        "errorCode": None,
        "errorMsg": None,
        "resultBody": file_info
    })
